<template>
  <view class="com-dishes-waterfall">
    <!-- prettier-ignore-attribute -->
    <kui-list-page
      ref="refKmfListPage"
      listHeight="90vh"
      :emptText="`暂无菜品`"
      :pam="lpOpt.pam"
      :requestApi="lpOpt.requestApi"
      :beforeReqHook="lpOpt.beforeReqHook"
      :useTabBar="lpOpt.useTopTabs"
      :useSearchBar="lpOpt.useSearchBar"
      searchPlaceholder=""
      :tabslist="lpOpt.tabslist"
      :tabsKey="lpOpt.tabsKey"
      :beforeSetDataHook="lpOpt.beforeSetDataHook"
    >
      <template #cusTabs>
        <view :class="['flex', 'p-5rpx', tabsStatus.isExpand ? 'tabs-expand' : 'tabs-scroll']">
          <view class="mr-5rpx" @click="changeTab('')">
            <u-button :type="!tabsValue ? 'primary' : 'info'">全部</u-button>
          </view>
          <view class="mr-5rpx tab-item" v-for="(item, index) in tabs" :key="index" @click="changeTab(item.value)">
            <u-button :type="tabsValue == item.value ? 'primary' : 'info'">{{ item.name }}</u-button>
          </view>

          <view class="absolute right-0">
            <u-button :type="'info'" custom-style="border:none;" @click="tabsStatus.isExpand = !tabsStatus.isExpand">
              <text class="mr-5rpx font-bold kui-color-theme text-base">{{
                tabsStatus.isExpand ? "收起" : "展开"
              }}</text>
              <u-icon
                :name="tabsStatus.isExpand ? 'arrow-down' : 'arrow-right'"
                color="var(--kui-color-theme)"
                bold
              ></u-icon>
            </u-button>
          </view>
        </view>
      </template>
      <!-- 自定义item -->
      <template v-slot:cusItem="{ list }">
        <view class="dishe-list">
          <itemDishe @click="itemDisheClick(item)" v-for="(item, index) in list" :noImageMode="noImageMode" :info="item" :key="index"> </itemDishe>
        </view>
      </template>
    </kui-list-page>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import itemDishe from "./item-dishe.vue";
import { getFoolTypeList, getFoodAppList } from "@/api";
import { useStore } from "vuex";
import { cloneDeep } from "lodash";
import { debounce } from "@kingon/app-tools";

const store = useStore();

const noImageMode = ref(store.getters.appSetting.noImageMode);

const lpOpt = reactive({
  pam: {
    dataType: 2,
    typeStatus: 1,
    descs: "create_time",
    userId: "", // 当前登录会员的id
    businessId: store.getters.businessInfo.businessId,
    name: "",
  },
  requestApi: getFoodAppList,
  beforeReqHook: (params) => {
    params.parentId = tabsValue.value;
    // 更新会员id
    const merberInfo = store.getters.currShoppingCardInfo?.member;
    if (merberInfo) params.userId = merberInfo.customerInformationId;
    return params;
  },
  beforeSetDataHook: async (res, pam) => {

    /**
     * 因为需要将菜单列表的已选数量和，购物车菜品数量同步，所以需要将返回的数据，进行一次处理
     */

    // 1.获取购物车菜品列表
    const cartList = store.getters.shoppingCart || [];
    return res.data.records.map((v) => {
      // 判断当前菜品是否在购物车中存在
      const cartItem = cartList.find((d) => d.foodTypeId == v.foodTypeId);
      if (cartItem && cartItem.count) {
        v.count = cartItem.count;
      } else {
        v.count = 0;
      }
      return v;
    });
  },
  useTopTabs: false,
  useSearchBar: false,
  tabslist: [],
  tabsKey: "type",
  // debugList: [],
});

// tabs
const tabs = ref([
  {
    name: "全部",
    value: 0,
  },
  {
    name: "特色菜",
    value: 1,
  },
  {
    name: "时蔬",
    value: 2,
  },
]);

const tabsValue = ref("");

const changeTab = (val) => {
  tabsValue.value = val;
  refKmfListPage.value.loadList();
};

const refKmfListPage = ref();

// 菜品点击
const itemDisheClick = (info) => {
  info.count = (Number(info.count) || 0) + 1;
  uni.$emit("cart-item:add", cloneDeep(info));
};

//


onMounted(async () => {
  try {
    const { id } = store.getters.userInfo;
    // 获取菜品分类
    const pam = {
      parentId: 0,
      dataType: 1,
      typeStatus: 1,
      businessId: id,
    };
    const { data, success } = await getFoolTypeList(pam);
    if (!success) throw new Error("获取菜品分类失败");
    tabs.value = data.map((v) => {
      return {
        name: v.name,
        value: v.foodTypeId,
      };
    });
  } catch (error) {
    console.error(error);
  }
  refKmfListPage.value.loadList();

  // 监听下拉刷新
  uni.$on("page:pull-downd-refresh", async () => {
    // 触发更新数据
    try {
      await refKmfListPage.value.loadList();
      uni.stopPullDownRefresh();
    } catch (error) {
      uni.stopPullDownRefresh();
    }
  });

  // 监听菜品搜索/清空
  uni.$on("page:search", async (value) => {
    console.log("搜索", value);
    lpOpt.pam.name = value;
    refKmfListPage.value.loadList();
  });

  // 处理数据更新
  const updateCount = (cartList, localData) => {
    return localData.map((v) => {
      // 判断当前菜品是否在购物车中存在
      const cartItem = cartList.find((d) => d.foodTypeId == v.foodTypeId);
      if (cartItem && cartItem.count) {
        v.count = cartItem.count;
      } else {
        v.count = 0;
      }
      return v;
    });
  };
  // 设置调用防抖
  const updatePage = debounce(() => {
    // console.log("setListData - 更新数据");
    // 1.获取购物车菜品列表
    const cartList = store.getters.shoppingCart;
    // 2.更新数据
    refKmfListPage.value.setListData((listData) => updateCount(cartList, listData));
  });
  // 监听购物车数据更新
  uni.$on("cart-item:update", updatePage);
});

onBeforeUnmount(() => {
  // 移除监听
  uni.$off("page:pull-downd-refresh");
  uni.$off("page:search");
  uni.$off("cart-item:update");
});

// 菜品类别操作条
const tabsStatus = reactive({
  // 是否展开
  isExpand: false,
});
</script>


<style lang="scss" scoped>
.com-dishes-waterfall {
  ::v-deep .kui-list-page {
    .u-sticky {
      top: 0 !important;
    }
  }

  .dishe-list {
    display: grid;
    margin-top: 10rpx;
    grid-template-columns: repeat(auto-fill, minmax(100rpx, 1fr));
    grid-gap: 10px;
    box-sizing: border-box;
    width: calc(100% - 10px);
  }
}

.tabs-expand {
  display: flex;
  flex-wrap: wrap;
  .tab-item {
    margin-bottom: 5rpx;
  }
}

.tabs-scroll {
  display: flex;
  overflow-x: scroll;
}
</style>
